<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="框架编号" prop="">
        <el-input v-model="queryParams.frameworkCode" placeholder="请输入框架编号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>

      <el-form-item label="发票编号" prop="no">
        <el-input v-model="queryParams.no" placeholder="请输入发票编号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="开票单位" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入开票单位" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="订单编号" prop="projectNo">
        <el-input v-model="queryParams.projectNo" placeholder="请输入订单编号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="是否已开票" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择是否开票" clearable style="width: 180px">
          <el-option v-for="dict in dict.type.invoice_apply_status" :key="dict.value" :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="回款状态" prop="fundCallback">
        <el-select v-model="queryParams.fundCallback" placeholder="请选择回款状态" clearable style="width: 180px">
          <el-option v-for="dict in dict.type.invoice_back_status" :key="dict.value" :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="项目单位" prop="companyName">
        <el-input v-model="queryParams.params['companyName']" placeholder="请输入项目单位" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="制单人" prop="createName">
        <el-input v-model="queryParams.params['createName']" placeholder="制单人" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="业务员" prop="salesmanName">
        <el-input v-model="queryParams.params['salesmanName']" placeholder="业务员" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>

      <el-form-item label="开票日期">
        <el-date-picker v-model="dateRange"
                        style="display: flex;"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button size="mini" type="primary" icon="el-icon-money" @click="handleAddInvoice('xmkp')">
          申请单个订单发票
        </el-button>
        <el-button size="mini" type="success" icon="el-icon-money" @click="addInvoiceAll()">
          申请订单批量发票
        </el-button>
        <el-button size="mini" type="warning" icon="el-icon-money" @click="addInvoiceHebing()">
          申请订单合并发票
        </el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>

      </el-form-item>
    </el-form>

    <el-table border v-loading="loading" :data="dataList" @selection-change="handleSelectionChange"
              show-summary :summary-method="getSummaries" :max-height="tableMaxHeight">
      <el-table-column label="框架编号" align="center" prop="frameworkCode"/>
      <el-table-column label="订单编号" align="center" prop="projectNo"/>
      <el-table-column label="开票单位" align="center" prop="customerName" show-overflow-tooltip/>
      <el-table-column label="开票单位编码" align="center" prop="taxNo"/>
      <el-table-column label="开票金额" align="center" prop="amount"/>
      <el-table-column label="已开" align="center" prop="amountReal"/>
      <el-table-column label="未开" align="center" prop="remaining"/>
      <el-table-column label="是否开票" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.invoice_apply_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="回款状态" align="center" prop="fundCallback">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.invoice_back_status" :value="scope.row.fundCallback"/>
        </template>
      </el-table-column>
      <el-table-column label="工程名称" align="center" prop="gongchengName" show-overflow-tooltip/>
      <el-table-column label="业务员" align="center" prop="saleName" show-overflow-tooltip/>
      <el-table-column label="申请人" align="center" prop="drawerName"/>
      <el-table-column sortable label="开票日期" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.invoiceDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)"
                     v-hasPermi="['develop:GoodsInvoice:edit']">查看详情
          </el-button>
          <el-popconfirm :title="`确认删除当前数据项？`" @confirm="handleDelete(scope.row)"
                         v-if="scope.row.status == '0' && scope.row.amountReal == 0" style="margin-left: 10px;">
            <el-button slot="reference" size="mini" type="text" icon="el-icon-delete">删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <goods-invoice-all-detail ref="invoiceAllDetail" @ok="getList"></goods-invoice-all-detail>
    <goods-invoice-batch @ok="getList" ref="goodsInvoiceBatch"></goods-invoice-batch>
    <goods-invoice-batch-all @ok="getList" ref="goodsInvoiceBatchAll"></goods-invoice-batch-all>
    <goods-invoice-batch-hebing @ok="getList" ref="goodsInvoiceBatchHebing"></goods-invoice-batch-hebing>
  </div>
</template>

<script>
import { deleteAction, getAction, updateAction, getById, downloadFile, accAdd } from '@/api/manage';
import GoodsInvoiceBatch from "./module/GoodsInvoiceBatch";
import GoodsInvoiceBatchHebing from "./module/GoodsInvoiceBatchHebing";
import GoodsInvoiceAllDetail from "@/views/develop/goodsInvoice/module/GoodsInvoiceAllDetail.vue";
import GoodsInvoiceBatchAll from "@/views/develop/goodsInvoice/module/GoodsInvoiceBatchAll.vue";

export default {
  name: "GoodsInvoiceList",
  dicts: ['fund_callback', 'yes_no', 'invoice_back_status', 'invoice_apply_status', 'invoice_type'],
  components: {
    GoodsInvoiceBatchAll,
    GoodsInvoiceAllDetail,
    GoodsInvoiceBatch,
    GoodsInvoiceBatchHebing,
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 发票管理表格数据
      dataList: [],
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        type: null,
        no: null,
        amount: null,
        amountReal: null,
        remaining: null,
        customerId: null,
        customerName: null,
        projectName: null,
        projectNo: null,
        taxNo: null,
        invoiceDate: null,
        invoiceCompany: null,
        fundCallback: null,
        backDate: null,
        drawerId: null,
        drawerName: null,
        saleId: null,
        saleName: null,
        createName: null,
        files: null,
        status: null,
        gongchengName: null,
        params: {}
      },
      url: {
        list: '/goodsInvoice/goodsInvoice/list',
        remove: '/goodsInvoice/goodsInvoice/',
        export: '/goodsInvoice/goodsInvoice/export',
      },
      tableMaxHeight: window.innerHeight - 320,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleAddInvoice(type) {
      this.$refs.goodsInvoiceBatch.showAddView(type);
    },
    addInvoiceAll() {
      this.$refs.goodsInvoiceBatchAll.showAddInvoiceAll();
    },
    addInvoiceHebing() {
      this.$refs.goodsInvoiceBatchHebing.showAddInvoiceHebing();
    },
    /** 修改发票号 */
    handleResetInvoiceNo(row) {
      this.$refs.formForCW.handleUpdateForCW(row);
    },

    /** 查询发票管理列表 */
    getList() {
      this.loading = true;
      this.addDateRange(this.queryParams, this.dateRange, 'InvoiceDate');
      getAction(this.url.list, this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.params = {}
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 详情按钮操作 */
    handleDetail(row) {
      this.$refs.invoiceAllDetail.handleDetail(row);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      deleteAction(this.url.remove, ids).then(response => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      let that = this;
      that.loading = false;
      that.$confirm('是否确认导出待核销信息表?', "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        downloadFile('/goodsInvoice/goodsInvoice/exportInvoice', that.queryParams);
      });
    },

    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (column.property === "amount"
          || column.property === 'amountReal'
          || column.property === 'remaining'
          || column.property === 'pinMoney'
          || column.property === 'pinRemain'
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev, curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },


  }
};
</script>
